package com.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.AOP.HasRole;
import com.project.common.R;
import com.project.dtoplus.PersonalInformation;
import com.project.entity.Login;
import com.project.entity.UserMember;
import com.project.mapper.UserMemberMapper;
import com.project.service.LoginService;
import com.project.service.UserMemberService;
import com.project.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserMemberController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private UserMemberService userMemberService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    UserMemberMapper userMemberMapper;

    //1.员工登录
    @PostMapping("/login")
    public R<String > login( @RequestParam String username,@RequestParam String password,@RequestParam int identity) throws UnsupportedEncodingException, JsonProcessingException {

        Integer a = identity;
        User user = new User();
        user.password=password;
        user.authType="password";
        user.identity= a.toString();
        user.username=username;

        // 2. 使用ObjectMapper将对象转换为JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String userJson = objectMapper.writeValueAsString(user);

        // 3. URL编码JSON字符串
        String encodedUserJson = URLEncoder.encode(userJson, StandardCharsets.UTF_8.toString());


        // 构建 URL
        String url = "http://localhost:8088/auth/oauth/token?client_id=XcWebApp&client_secret=XcWebApp&grant_type=password&username=" + encodedUserJson;

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 创建 HttpEntity 对象，包含请求体和请求头
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);

        // 发送 POST 请求并获取响应
        String response = restTemplate.postForObject(url, requestEntity, String.class);
        System.out.println(response);
        Map<String, String> resultMap = new HashMap<>();
        try {
            ObjectMapper objectMapper1 = new ObjectMapper();
            // 先将JSON字符串转换为Map<String, Object>
            Map<String, Object> jsonMap = objectMapper1.readValue(response, Map.class);

            // 将所有值转换为String类型
            for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
                resultMap.put(entry.getKey(), String.valueOf(entry.getValue()));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


        return R.success(resultMap.get("access_token"));


    }

    public class User{
        public String username;
        public String password;
        public String identity;
        public String authType;
        @Override
        public String toString() {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                return objectMapper.writeValueAsString(this);
            } catch (JsonProcessingException e) {
                throw new RuntimeException("Failed to convert User to JSON", e);
            }
        }


    }
    //2.退出功能
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request , HttpServletResponse response){

        String authorization = request.getHeader("token");
        if (authorization != null && authorization.startsWith("Bearer ")) {
            String token = authorization.substring(7); // 去掉 "Bearer " 前缀
            // 处理 token
            JwtUtils.addToBlacklist(token);
        }


        return R.success("退出成功");
    }
    @HasRole(2)
    //3.管理员添加用户
    @PostMapping("/add")
    public R<String> add(HttpServletRequest request,@RequestBody UserMember userMember){

        userMemberService.add(request,userMember);
        return R.success("添加成功");
    }

    //4.用户首次登陆时——获取登录信息
    @GetMapping("/loginInf")
    public R<PersonalInformation> loginInf(){
        PersonalInformation login = userMemberService.obtain();

        return R.success(login);
    }

    //5. 修改密码
    @PutMapping("/changePassword")
    public R<String> change(@RequestBody Login login){
        String changeInfo = userMemberService.changeInfo(login);
        return R.success(changeInfo);
    }
   //6.获取用户身份
    @GetMapping("/identity")
    public int identity(@RequestParam Long userId){
        int identity = userMemberMapper.getIdentity(userId);
        return identity;
    }


}
